package com.itheima.zhlx.controller;

import com.alibaba.fastjson.JSONObject;
import com.itheima.zhlx.entity.PageBean;
import com.itheima.zhlx.entity.PageTotal;
import com.itheima.zhlx.entity.Result;
import com.itheima.zhlx.pojo.Goods;
import com.itheima.zhlx.service.GoodsServlce;
import com.itheima.zhlx.service.impl.GoodsServlceImpl;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/goods")
public class GoodsServlet extends BaseServlet {
    private GoodsServlce goodsServlce =new GoodsServlceImpl();

   public void findPage(HttpServletRequest request,HttpServletResponse response){
       // 获取前端传进来的当前页和每页需要展示条多少数据
       String currentPage = request.getParameter("currentPage");
       String pageSize = request.getParameter("pageSize");
       PageBean pageBean =new PageBean();
       //封装类 准备传给servlet层
       pageBean.setCurrentPage(Integer.parseInt(currentPage));
       pageBean.setPageSize(Integer.parseInt(pageSize));
       PageTotal pageTotal = goodsServlce.goodfindAll(pageBean);
       //把查询到的结果封装到Result类中 返回给前端
       Result result =new Result(true,"成功",pageTotal);
       try {
           //因为前端需要的是json数据 所以需要转换
           response.getWriter().print(JSONObject.toJSON(result));
       } catch (IOException e) {
           e.printStackTrace();
       }

   }
   public void addGoods(HttpServletRequest request,HttpServletResponse response){
       //将前端传来的参数转换成json数据
       try {
           Goods goods = JSONObject.parseObject(request.getInputStream(), Goods.class);

           Integer integer = goodsServlce.addGoods(goods);

           if (integer>0){
               Result result =new Result(true,"添加成功",integer);
               response.getWriter().print(JSONObject.toJSONString(result));
           }else {
               Result result =new Result(false,"添加失败",integer);
               response.getWriter().print(JSONObject.toJSONString(result));
           }
       } catch (IOException e) {
           e.printStackTrace();
       }
   }
   public void delete(HttpServletRequest request,HttpServletResponse response){
       try {
           String id = request.getParameter("id");
           Integer integer = goodsServlce.deleteGoods(id);
           if (integer>0){
               Result result =new Result(true,"删除成功",integer);
               response.getWriter().print(JSONObject.toJSONString(result));
           }else {
               Result result =new Result(false,"删除失败",integer);
               response.getWriter().print(JSONObject.toJSONString(result));
           }
       } catch (IOException e) {
           e.printStackTrace();
       }

   }



}
